import { Hono } from 'hono';
import { html } from 'hono/html';
// import { ipRestriction } from 'hono/ip-restriction';
import type { AI, KVNamespace } from './env';
import book from './routers';

declare global {
  let AI: AI;
  let my_kv: KVNamespace;
}

const app = new Hono().basePath('/');

app.route('/book', book);

// 只要 /api 开头
// 需要将 index.tsx、[[default]].ts 文件 移动到 functions/api 文件夹
// const app = new Hono().basePath('/api');

// ip  限制
// app.use(
//   '*',
//   ipRestriction(
//     c => ({
//       remote: {
//         // @ts-expect-error
//         address: c.req.raw.eo.clientIp,

//         addressType:
//           String(
//             // @ts-expect-error
//             c.req.raw.eo.clientIp
//           ).indexOf('::') === -1
//             ? 'IPv4'
//             : 'IPv6'
//       }
//     }),
//     {
//       denyList: [],
//       allowList: [ '127.0.0.1', '::1']
//     }
//   )
// );

interface SiteData {
  title: string;
  children?: any;
}

const Layout = (props: SiteData) =>
  html`
    <!DOCTYPE html>
    <html>
      <head>
        <title>${props.title}</title>
      </head>
      <body>
        ${props.children}
      </body>
    </html>
  `;

const Content = (props: { siteData: SiteData; name: string }) => (
  <Layout {...props.siteData}>
    <h1>Hello {props.name}</h1>
  </Layout>
);

app.get('/:name', c => {
  const { name } = c.req.param();
  const props = {
    name: name,
    siteData: {
      title: 'JSX with html sample'
    }
  };
  return c.html(<Content {...props} />);
});

app.get('/', async c => {
  // console.log(c.req.raw.eo.geo);
  // console.log(c.req.raw.eo.clientIp);

  return c.html('<h1>Hello World</h1>', 200, {
    'Content-Type': 'text/html'
  });
});

// ai
app.post('/v1/chat/completions', async c => {
  const body = await c.req.json();

  const response = await AI.chatCompletions(body);

  try {
    if (body.stream) {
      return new Response(response, {
        headers: {
          'Content-Type': 'text/event-stream',
          'Cache-Control': 'no-cache',
          Connection: 'keep-alive',
          'Access-Control-Allow-Origin': '*',
          'Access-Control-Allow-Methods': 'POST, OPTIONS',
          'Access-Control-Allow-Headers': 'Content-Type, Authorization'
        }
      });
    } else {
      return new Response(response, {
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*',
          'Access-Control-Allow-Methods': 'POST, OPTIONS',
          'Access-Control-Allow-Headers': 'Content-Type, Authorization'
        }
      });
    }
  } catch (error: any) {
    return new Response(
      JSON.stringify({
        error: 'AI_SERVICE_ERROR',
        message: error.message
      }),
      { status: 503 }
    );
  }
});

// 文件上传
app.post('/upload', async c => {
  const body = await c.req.parseBody();
  console.log(body['file'], 111);

  return c.text('OK');
});

app.notFound(c => {
  return c.text('Custom 404 Message', 404);
});

app.onError((err, c) => {
  console.error(`${err}`);
  return c.text('Custom Error Message', 500);
});

// export default app;

export function onRequest(context: {
  request: Request;
  params: Record<string, string>;
  env: Record<string, any>;
}): Response | Promise<Response> {
  return app.fetch(context.request, context.env);
}
